package com.example.common.cqsupervision.utils;

import java.util.UUID;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import com.example.common.support.ApiException;

import org.apache.commons.codec.binary.Base64;

public class Sgin {

    public Sgin(){
        this.setXRbTimestamp();
        this.setXRbRequuid();
    }

    private String x_rb_key;
    public String getXRbKey(){
        return x_rb_key;
    }
    public void setXRbKey(String x_rb_key){
        this.x_rb_key = x_rb_key;
    }

    private long x_rb_timestamp;

    public Long getXRbTimestamp() {
        return x_rb_timestamp;
    }
 
    private void setXRbTimestamp() {
        this.x_rb_timestamp = System.currentTimeMillis();
    }

    private String x_rb_requuid;
    public String getXRbRequuid() {
        return x_rb_requuid;
    }
 
    private void setXRbRequuid() {
        this.x_rb_requuid = UUID.randomUUID().toString();
    }

    private String secret;
    public void setSecret(String secret){
        this.secret = secret;
    }

    public String doSign(){
        if(secret == null || secret.length() == 0)
            throw new ApiException(1,"secret不能为空");
        try {            
            Mac hmacSha256 = Mac.getInstance("HmacSHA256");
            byte[] keyBytes = secret.getBytes("UTF-8");
            hmacSha256.init(new SecretKeySpec(keyBytes, 0, keyBytes.length, "HmacSHA256"));
            String textToSign = this.getXRbTimestamp() + this.getXRbRequuid();
            String sign = Base64.encodeBase64String(hmacSha256.doFinal(textToSign.getBytes("UTF-8")));
            return sign;
        } catch (Exception e) {
            //TODO: handle exception
        }
        return "";
    }
}
